package com.zhangtai.modules.controller.member;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhangtai.modules.constVo.NoticeConst;
import com.zhangtai.modules.constVo.ScoreConst;
import com.zhangtai.modules.controller.admin.JobController;
import com.zhangtai.modules.controller.admin.NoticeController;
import com.zhangtai.modules.controller.aouthLogin.MemberLoginController;
import com.zhangtai.modules.dao.ScoreDao;
import com.zhangtai.modules.dao.ScoreProgramTopicDao;
import com.zhangtai.modules.dao.ScoreRaterDao;
import com.zhangtai.modules.dao.ScoreTopicDao;
import com.zhangtai.modules.dto.ScoreRaterDto;
import com.zhangtai.modules.dto.ScoreTopicDto;
import com.zhangtai.modules.dto.ScoreTopicScoreDto;
import com.zhangtai.modules.entity.score.*;
import com.zhangtai.modules.service.sroce.*;
import com.zhangtai.modules.vo.ScoreRaterVo;
import com.zhangtai.utils.PageResult;
import com.zhangtai.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@RequestMapping("/member")
@Slf4j
@Api(tags="360评价自助端")
@RestController()
public class ScoreMemberController {
    @Autowired
    private ScoreRaterDao scoreRaterDao;
    @Autowired
    private MemberLoginController memberLoginController;
    @Autowired
    private ScoreProgramTopicDao scoreProgramTopicDao;
    @Autowired
    private JobController jobController;
    @Autowired
    private ScoreRaterService scoreRaterService;
    @Autowired
    private ScoreTopicDao scoreTopicDao;
    @Autowired
    private ScoreTopicService scoreTopicService;
    @Autowired
    private ScoreDao scoreDao;
    @Autowired
    private ScoreService scoreService;
    @Autowired
    private ScoreWeightsService scoreWeightsService;
    @Autowired
    private ScoreProgramService scoreProgramService;
    @Autowired
    private NoticeController noticeController;

    @PostMapping("/getRaterPage")
    @ApiOperation("分页获取个人360评价信息")
    public R getRaterPage( @RequestParam(value = "status",required = false) Integer status,
                           @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                           HttpServletRequest request)throws Exception{
        JSONObject userInfo = memberLoginController.getUserInfo(request).getData();
        if(ObjectUtils.isEmpty(userInfo)){
            return R.error("请登录");
        }
        Long oid = userInfo.getLong("id");
        Page<ScoreRaterDto> page = new Page<ScoreRaterDto>(pageNum,pageSize);
        List<ScoreRaterDto> scoreRaterDtoList = scoreRaterDao.getScoreScorePage(oid,status,page);
        for (ScoreRaterDto scoreRaterDto : scoreRaterDtoList){
            if(scoreRaterDto.getJobId()!=null) scoreRaterDto.setJobName(jobController.getJobName(scoreRaterDto.getJobId()));
            if(scoreRaterDto.getOrgId()!=null) scoreRaterDto.setOrgName(jobController.getOrgNameById(scoreRaterDto.getOrgId()));
            if(scoreRaterDto.getUnitId()!=null) scoreRaterDto.setUnitName(jobController.getOrgNameById(scoreRaterDto.getUnitId()));
        }
        page.setRecords(scoreRaterDtoList);
        return R.ok(new PageResult<ScoreRaterDto>(page));
    }

    @PostMapping("/getTopicInfo")
    @ApiOperation("获取360评价题目信息")
    public R getTopicInfo(@RequestParam(value = "programId") String programId){
        List<ScoreTopicDto> scoreTopicDtoList= scoreProgramTopicDao.getScoreTopic(Long.valueOf(programId));
        return R.ok(scoreTopicDtoList);
    }
    @PostMapping("/saveRaterTopicInfo")
    @ApiOperation("保存360评价题目分数信息")
    @Transactional
    public R saveRaterTopicInfo(@RequestBody @Valid ScoreRaterVo scoreRaterVo){
        R r;
        ScoreRaterEntity scoreRaterEntity= scoreRaterService.getByIdE(scoreRaterVo.getId());
        if (2==scoreRaterEntity.getStatus()){
            return R.error("该评价已终止，无法提交分数！");
        }
        scoreRaterEntity.setStatus(1);
        scoreRaterEntity.setScoreTime(new Date());
        BigDecimal sum=new BigDecimal(0);
        for (ScoreTopicScoreDto scoreTopicScoreDto:scoreRaterVo.getScoreTopicScoreDtoArrayList()){
            sum=sum.add(scoreTopicScoreDto.getScore());
            ScoreTopicEntity scoreTopicEntity= scoreTopicService.getByIdE(scoreTopicScoreDto.getId());
            scoreTopicScoreDto.setMaxScore(scoreTopicEntity.getMaxScore());
            scoreTopicScoreDto.setTitle(scoreTopicEntity.getTitle());
        }
        scoreRaterEntity.setRaterScore(sum);
        scoreRaterEntity.setScoreArray(JSONObject.toJSONString(scoreRaterVo.getScoreTopicScoreDtoArrayList()));
        r= scoreRaterService.updateByIdE(scoreRaterEntity);

        //将待转正待办设置为完成
        noticeController.updateNoticeTodo(scoreRaterEntity.getId(), NoticeConst.MSG_TYPE_SCORE);

        List<ScoreRaterEntity> scoreRaterEntityList=scoreRaterDao.selectList(new QueryWrapper<ScoreRaterEntity>()
                .eq("score_id",scoreRaterEntity.getScoreId())
                .eq("is_delete",0).eq("status",1));
        ScoreEntity scoreEntity= scoreService.getByIdE(scoreRaterEntity.getScoreId());
        scoreEntity.setAppraisalNum(scoreRaterEntityList.size());
        scoreEntity.setAppraisalTare(new BigDecimal(scoreRaterEntityList.size()*100).divide(new BigDecimal(scoreEntity.getSum()),2, BigDecimal.ROUND_HALF_UP));
        if(!CollectionUtils.isEmpty(scoreRaterEntityList)&&scoreEntity.getSum()==scoreRaterEntityList.size()){
            scoreEntity.setStatus(2);
            BigDecimal score=new BigDecimal(0);
            BigDecimal weights=new BigDecimal(0);
            for(ScoreRaterEntity scoreRater:scoreRaterEntityList){
                score=score.add(scoreRater.getRaterScore().multiply(scoreRater.getWeights()));
            }
            ScoreProgramEntity scoreProgramEntity=  scoreProgramService.getByIdE(scoreEntity.getProgramId());
            ScoreWeightsEntity scoreWeightsEntity=scoreWeightsService.getByIdE(scoreProgramEntity.getWeightsId());
            weights= getWeights(weights,scoreEntity.getId(),scoreWeightsEntity.getSuperiorWeights(), ScoreConst.SCORE_SUPERIOR_EIGHTS_TYPE);
            weights= getWeights(weights,scoreEntity.getId(),scoreWeightsEntity.getSameLevelWeights(), ScoreConst.SCORE_SAME_LEVEL_EIGHTS_TYPE);
            weights= getWeights(weights,scoreEntity.getId(),scoreWeightsEntity.getSubordinateWeights(), ScoreConst.SCORE_SUBORDINATE_EIGHTS_TYPE);
            weights= getWeights(weights,scoreEntity.getId(),scoreWeightsEntity.getMyWeights(), ScoreConst.SCORE_MY_EIGHTS_TYPE);

            scoreEntity.setScore(weights.compareTo(BigDecimal.ZERO)==0?weights:score.divide(weights,2, BigDecimal.ROUND_HALF_UP));
        }
        r=  scoreService.updateByIdE(scoreEntity);
        return  r;
    }

    private BigDecimal getWeights(BigDecimal weights,Long scoreId,BigDecimal RoleWeights,Integer type){
        List<ScoreRaterEntity> scoreRater=scoreRaterDao.selectList(new QueryWrapper<ScoreRaterEntity>()
                .eq("score_id",scoreId)
                .eq("is_delete",0).eq("status",1).eq("type", type));
        if(!CollectionUtils.isEmpty(scoreRater)){
            weights=weights.add(RoleWeights);
        }
        return weights;
    }


    @GetMapping("/getSoreTopicScore")
    @ApiOperation("获取360评价题目提交的分数")
    public R getSoreTopicScore(@RequestParam(value = "id") String id){
        ScoreRaterEntity scoreRaterEntity= scoreRaterService.getByIdE(Long.valueOf(id));
        List<ScoreTopicScoreDto> scoreTopicScoreDtoList= JSONObject.parseArray(scoreRaterEntity.getScoreArray(), ScoreTopicScoreDto.class);
        return R.ok(scoreTopicScoreDtoList);
    }

}
